package com.sys.basics.service.impl;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import com.sys.basics.entity.SysArea;
import com.sys.basics.dao.SysAreaDao;
import com.sys.basics.service.SysAreaService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;


/**
 * @author: ares
 * @date: 2021-10-08
 * @description: 行政区域表 服务实现类
 */
@Slf4j
@Service
public class SysAreaServiceImpl extends ServiceImpl<SysAreaDao, SysArea> implements SysAreaService {
    @Autowired
	SysAreaDao sysAreaDao;

    public SysArea getTreeByCode(String areaCode) {
        return sysAreaDao.getTreeByCode(areaCode);
    }

    @Override
    public List<SysArea> getChildrenTreeByParentCode(String parentId) {
        return sysAreaDao.getChildrenTreeByParentCode(parentId);
    }

    @Override
    public List<SysArea> getChildrenByParentCode(String areaCode) {
        return sysAreaDao.getChildrenByParentCode(areaCode);
    }

    /**
     * @param areaCode
     * @return
     * @author: ares
     * @date: 2021/9/30 21:06
     * @description: 根据子节点code查询上级tree
     */
    @Override
    public SysArea getTreeByCodeAsLeaf(String areaCode) {
        return getParent(sysAreaDao.getByCode(areaCode));
    }


    /**
     * @param children
     * @return
     * @author: ares
     * @date: 2021/9/30 22:10
     * @description: 根据子节点查询父节点
     */
    private SysArea getParent(SysArea children) {
        if(children == null) return null;
        String parentCode = children.getParentCode();
        if (parentCode.equals("0")) {
            return children;
        } else {
            SysArea parent = sysAreaDao.getByCode(parentCode);
            parent.setChildren(Arrays.asList(children));
            return getParent(parent);
        }
    }

    /**
     * @author: ares
     * @date: 2021/10/1 21:10
     * @description: 根据code删除自身及子节点
     * @param areaCode
     * @return
     */
    @Override
    public boolean removeSelfAndChildrenByCode(String areaCode) {
        List<SysArea> children = sysAreaDao.getChildrenByParentCode(areaCode);
        if (children.size() > 0) {
            children.forEach(child -> removeSelfAndChildrenByCode(child.getAreaCode()));
        }
        return sysAreaDao.removeByCode(areaCode);
    }

}
